package com.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

import com.model.Tarefa;

public class DBManager{

	private static DB db = new DB();

	public static enum AllocMod {MANUAL, FIFO, PRIORIDADE, DEADLINE};
	
	public static AllocMod getAllocModSel() {
		return db.allocModSel;
	}
	
	public static void setAllocModSel(AllocMod allocModSel) {
		db.allocModSel = allocModSel;
	}
	
	public static void addNova(Tarefa t){
		db.tarefas.add(t);
	}

	public static void updTarefa(Tarefa t) {
		ListIterator<Tarefa> iterator = DBManager.getIterator();
		while(iterator.hasNext()){
			Tarefa old = iterator.next();
			if(old.getDescricao().equals(t.getDescricao())){
				old.setInicio(t.getInicio());
				old.setDeadLine(t.getDeadLine());
				old.setEsforcoDiario(t.getEsforcoDiario());
				old.setEsforcoTotal(t.getEsforcoTotal());
				old.setRepeticao(t.getRepeticao());
				old.setGrave(t.getGrave());
				old.setUrgente(t.getUrgente());
				old.setVaiPiorar(t.getVaiPiorar());
				break;
			}
		}
	}

	public static void delete(Tarefa t){
		db.tarefas.remove(t);
	}
	
	public static ListIterator<Tarefa> getIterator(){
		return db.tarefas.listIterator();
	}

	public static Tarefa getTarefa(String desc) {
		ListIterator<Tarefa> iterator = DBManager.getIterator();
		while(iterator.hasNext()){
			Tarefa t = iterator.next();
			if(t.getDescricao().equals(desc))
				return t;
		}
		return null;
	}
	
	public static List<Tarefa> getAll(){
		List<Tarefa> all = new ArrayList<>();
		ListIterator<Tarefa> iterator = DBManager.getIterator();
		while(iterator.hasNext()){
			Tarefa t = iterator.next();
			all.add(t);
		}
		return all;
	}
	
	public static void save(){
		String dir = System.getProperty("user.dir");
		File f = new File(dir, "dados.db");
		try {
			FileOutputStream fos = new FileOutputStream(f);
			ObjectOutputStream oos = new ObjectOutputStream(fos);
			oos.writeObject(db);
			oos.flush();			
			oos.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
	
	public static void load(){
		String dir = System.getProperty("user.dir");
		File f = new File(dir, "dados.db");
		if(f.exists())
			try {
				FileInputStream fis = new FileInputStream(f);
				ObjectInputStream ois = new ObjectInputStream(fis);
				db = (DB) ois.readObject();
				ois.close();
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}		
	}

	static class DB implements Serializable{
		
		private static final long serialVersionUID = 1L;
		
		public AllocMod allocModSel = DBManager.AllocMod.MANUAL;
		public ArrayList<Tarefa> tarefas = new ArrayList<>();
		
	}

}
